<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class kst_sttb extends MY_Controller {
	
	function __construct()
	{
		parent::__construct(); 
		
		// Uses Model
		$this->load->model('kst_sttb_model', 'Master');
		$this->load->model('kst_detail_sttb_model', 'Detail');
		$this->load->model('kst_combo_model', 'Combo');
		$this->load->model('kst_store_procedure_model', 'SP');
		// Secure Page With Session
		$this->secure_session();
	}
	
	function index(){
		// Display Index
		$data['title'] = $this->session_menu_label;
		
		viewByTemplate('kst_sttb/index', $data, 'grid');
	}
	
	function getdata()
	{
		// Ajax Response For Datagrid
		echo $this->Master->GetJSON();
	}
		
	function dtl_sample2_data()
	{
		// Ajax Response For Datagrid
		echo $this->Detail->GetJSON(post('no_po'));
	}
	
	
	function edit()
	{
		// Display Form Edit
		$data['title'] = "Ubah Pembelian";
		$data['data'] = $this->Master->GetSingleView(get('no_po'));
		
		$data['mode'] = "edit";
		viewByTemplate('kst_sttb/form', $data, 'form');	
		
	}
	
	function view()
	{
		// Display Form View
		$data['title'] = "View Data Master";
		$data['data'] = $this->Master->GetSingleView(get('no_po'));
		
		$data['mode'] = "view";
		viewByTemplate('kst_sttb/form', $data, 'form');
	}

	private function validation()
	{
		$error = new ErrorList();

		// Get Error Template
		$tpl_empty		= $this->MessageTemplate("ER001");
		$tpl_duplicate	= $this->MessageTemplate("ER002");
		// Validation
		if (post("or_sttb_no") == '') {
			$error->Add("or_sttb_no", "No STTB", $tpl_empty);
		} else if (post("mode") == "create" && intval($this->get_data("SELECT COUNT(1) FROM kst_order_receive WHERE UPPER(or_sttb_no) = '".@strtoupper(@trim(post("or_sttb_no")))."'")) > 0) {
			$error->Add("or_sttb_no", "No STTB", $tpl_duplicate);
		}
		
		return $error;
	}
	
	function ajax_post()
	{
		// Ajax Response For Submit Form
		$is_error = 0;
		$ls_response = "";
		$ls_genid = "";
		
		// Get Error Template
		$tpl_insert_success = $this->MessageTemplate("CS001");
		$tpl_update_success = $this->MessageTemplate("CS002");
		
		$error = $this->validation();
		try
		{
			if (count( $error->Get() ) > 0) { $is_error = 1; }
			else
			{
				// Fill Post Data Array
				$data	= post_by_key(array('or_po_no','or_sttb_no','or_po_date','or_sttb_date','or_sttb_jatuhtempo'));
				
				// Set Primary Key Variable
				$data['or_po_no']	= @strtoupper(@trim(post("or_po_no")));
				$data['or_sttb_no']	= @strtoupper(@trim(post("or_sttb_no")));
				$no_po	= $data['or_po_no'];
				$no_sttb = $data['or_sttb_no'];
				
				// Set Date Format
				$data['or_po_date']	= ($data['or_po_date'] == '' ? NULL : date_format3($data['or_po_date'], 'YYYY-MM-DD'));	
				$data['or_sttb_date']	= ($data['or_sttb_date'] == '' ? NULL : date_format3($data['or_sttb_date'], 'YYYY-MM-DD'));
				$data['or_sttb_jatuhtempo']	= ($data['or_sttb_jatuhtempo'] == '' ? NULL : date_format3($data['or_sttb_jatuhtempo'], 'YYYY-MM-DD'));			
				
				if (post("mode") == "create")
				{

					$ls_genid	= $no_po;
					$this->Master->Add($data);					
					$ls_response = "Data Tersimpan";
				}
				else if (post("mode") == "edit")
				{

					unset($data['or_po_no']);
					
					$this->Master->Update($data, array('or_po_no' => $no_po));
					
					$ls_response = "Data Tersimpan [edited]";
					
				}
								
				// ----- >> Detail Sample 2
				$dtl_sample2	= $this->data['dtl_sample2'];
				$total_deleted	= $dtl_sample2['num_row']['deleted'];
				$total_inserted	= $dtl_sample2['num_row']['inserted'];
				$total_updated	= $dtl_sample2['num_row']['updated'];
				for($i=0,$max_i=$total_deleted; $i<$max_i; $i++){
					$row = $dtl_sample2['deleted'][$i];
					
					$this->Detail->DeleteSingle($row['no_po']);
				}
				for($i=0,$max_i=$total_inserted; $i<$max_i; $i++){
					$row = $dtl_sample2['inserted'][$i];
					
					$row['qty_order'] = (float)$row['qty_order'];
					$row['kd_barang'] = $kd_barang;
					$row['no_po'] = $no_po;
					$row['no_sttb'] = $no_sttb;
					$row['qty_terima'] = (float)$row['qty_terima'];
					
					$this->Detail->Add($row);
				}
				for($i=0,$max_i=$total_updated; $i<$max_i; $i++){
					$row = $dtl_sample2['updated'][$i];					
					$urutan	= $row['urutan'];
					unset($row['urutan']);
					
					$row['qty_order'] = (float)$row['qty_order'];
					$row['no_sttb'] = $no_sttb;
					//$row['qty_terima'] = (float)$row['qty_terima'];
					
					$this->Detail->Update($row, array(	'no_po'	=> $no_po, 
														'urutan'	=> $urutan));
														
												
				}
			}
		} catch(Exception $e) {
			$is_error = 1; $ls_response = $e->getMessage();
		}
		
		echo $this->PostResponse(json_encode(array(	'is_error'	=> $is_error,
													'fields'	=> $error->GetDictionary(),
													'msg'		=> $ls_response,
													'genid'		=> $ls_genid,
													'form_sender'=> post("form_sender"))
								));
	}
	
	function cetak(){
		$no_po	= get('no_po');
		
		if($no_po!='' && $no_po!=''){
			
			// Load FPDF
			$this->load->helper('fpdf');
			
			// Set Data
			$data['data'] = $this->Master->GetSingleView($no_po);
			//$data['arr_detail']	= $this->Detail->GetDetailByID($no_po);
			
			// Load View
			$this->load->view('kst_sttb/cetak', $data);
			
		}
	}
		
	function ajax_delete()
	{
		$ls_result	= "";
		$no_po	= get('no_po');
		
		if ($no_po != "")
		{
			// Delete Single
			$arr_rule	= array('no_po' => $no_po);
			$ls_result = $this->Master->DeleteSingle($arr_rule);
		}
		else
		{
			$num_row = intval($this->data['num_row']['deleted']);
			
			for ($i = 0; $i < $num_row; $i++)
			{
				$row	= $this->data['deleted'][$i];
				
				$arr_rule	= array('no_po' => $row['no_po']);
				$ls_result .= $this->Master->DeleteSingle($arr_rule);
			}
						
		}
		
		echo $ls_result;
	}

	function print_excel()
	{
		$no_po	= get('no_po');
		
		if($no_po!=''){			
			// Set Data
			$data = $this->Master->GetSingleView($no_po);
			$data_detail = $this->Master->GetForExcel($no_po);
			
			$x=0;

			$this->load->library('excel');
			$this->excel->setActiveSheetIndex(0);
			//name the worksheet
			$this->excel->getActiveSheet()->setTitle('STTB '. $data['no_po']);

			$no = 1;

			if ($data) {
				$styleArrayBorder = array(
					'borders' => array(
						'allborders' => array(
						'style' => PHPExcel_Style_Border::BORDER_THIN
						)
					)
				);

				$this->excel->getActiveSheet()->setCellValue('A2', 'STTB');
				$this->excel->getActiveSheet()->setCellValue('A5', 'NO PO');
				$this->excel->getActiveSheet()->mergeCells('A5:B5');
				$this->excel->getActiveSheet()->setCellValue('C5', ': '.$data['no_po']);
				$this->excel->getActiveSheet()->setCellValue('A6', 'NO STTB');
				$this->excel->getActiveSheet()->mergeCells('A6:B6');
				$this->excel->getActiveSheet()->setCellValue('C6', ': '.$data['no_sttb']);
				$this->excel->getActiveSheet()->setCellValue('A7', 'KODE VENDOR');
				$this->excel->getActiveSheet()->mergeCells('A7:B7');
				$this->excel->getActiveSheet()->setCellValue('C7', ': '.$data['kd_vendor']);
				$this->excel->getActiveSheet()->setCellValue('A8', 'TANGGAL ORDER');
				$this->excel->getActiveSheet()->mergeCells('A8:B8');
				$this->excel->getActiveSheet()->setCellValue('C8', ': '.$data['tgl_order']);
				$this->excel->getActiveSheet()->setCellValue('A9', 'TANGGAL TERIMA');
				$this->excel->getActiveSheet()->mergeCells('A9:B9');
				$this->excel->getActiveSheet()->setCellValue('C9', ': '.$data['tgl_terima']);
				$this->excel->getActiveSheet()->setCellValue('A10', 'TANGGAL JATUUH TEMPO');
				$this->excel->getActiveSheet()->mergeCells('A10:B10');
				$this->excel->getActiveSheet()->setCellValue('C10', ': '.$data['tgl_jatuh_tempo']);
				$this->excel->getActiveSheet()->setCellValue('A11', 'JENIS PEMBAYARAN');
				$this->excel->getActiveSheet()->mergeCells('A11:B11');
				$this->excel->getActiveSheet()->setCellValue('C11', ': '.$data['jenis_pembayaran']);

				$this->excel->getActiveSheet()->getStyle('A5:C11')->getFont()->setBold(true);

				$this->excel->getActiveSheet()->setCellValue('A13', 'NO');
				$this->excel->getActiveSheet()->setCellValue('B13', 'ITEMS');
				$this->excel->getActiveSheet()->setCellValue('C13', 'SATUAN KEMASAN');
				$this->excel->getActiveSheet()->setCellValue('D13', 'SATUAN ORDER');
				$this->excel->getActiveSheet()->setCellValue('E13', 'PRICE');
				$this->excel->getActiveSheet()->setCellValue('F13', 'ORDER');
				$this->excel->getActiveSheet()->setCellValue('G13', 'TOTAL');

				$this->excel->getActiveSheet()->getStyle('A13:G13')->getFont()->setBold(true);
				$this->excel->getActiveSheet()->getStyle('A13:G13')->getFill()->applyFromArray(array('type' => PHPExcel_Style_Fill::FILL_SOLID,'startcolor' => array('rgb' => 'EEEE11')));
				$this->excel->getActiveSheet()->getStyle('A13:G13')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

				$x = 13;
				for($i=0;$i<=$data_detail['total']-1;$i++){
					$x++;

					$rows = $data_detail['rows'];
					$rows2 = $rows[$i];

					$this->excel->getActiveSheet()->setCellValue('A'.$x, $no);
					$this->excel->getActiveSheet()->setCellValue('B'.$x, $rows2['nama_barang']);
					$this->excel->getActiveSheet()->setCellValue('C'.$x, '-');
					$this->excel->getActiveSheet()->setCellValue('D'.$x, '-');
					$this->excel->getActiveSheet()->setCellValue('E'.$x, $rows2['harga']);
					$this->excel->getActiveSheet()->setCellValue('F'.$x, $rows2['qty_order']);
					$this->excel->getActiveSheet()->setCellValue('G'.$x, $rows2['qty_order']*$rows2['harga']);

					$no++;
				}
			}
			

			$styleArray = array(
				'borders' => array(
				    'allborders' => array(
				    'style' => PHPExcel_Style_Border::BORDER_THIN
				    )
				),
				'font'  => array(
				    'size'  => 10,
				    'name'  => 'verdana'
				)
			);

			$this->excel->getActiveSheet()->getStyle('A13:G'.$x)->applyFromArray($styleArray);
			unset($styleArray);

			$styleArray1 = array(
			    'font'  => array(
				    'bold'  => true,
				    'uppercase' => true,
				    'size'  => 18,
				    'name'  => 'Calibri'
			    )
			);
			$this->excel->getActiveSheet()->getColumnDimension('A')->setWidth(7);
			$this->excel->getActiveSheet()->getColumnDimension('B')->setWidth(30);
			$this->excel->getActiveSheet()->getColumnDimension('C')->setWidth(22);
			$this->excel->getActiveSheet()->getColumnDimension('D')->setWidth(22);
			$this->excel->getActiveSheet()->getColumnDimension('E')->setWidth(15);
			$this->excel->getActiveSheet()->getColumnDimension('F')->setWidth(15);
			$this->excel->getActiveSheet()->getColumnDimension('G')->setWidth(22);
			

			//set aligment to center for that merged cell (A1 to D1)
			$this->excel->getActiveSheet()->mergeCells('A2:G2');
			$this->excel->getActiveSheet()->getStyle('A2:G2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
			$this->excel->getActiveSheet()->getStyle('A2:G2')->applyFromArray($styleArray1);
			unset($styleArray1);
			//$this->excel->getActiveSheet()->getStyle('A2:G2')->getFont()->setBold(true);

			$filename= 'STTB '.$data['no_po'].'.xls'; //save our workbook as this file name
			header('Content-Type: application/vnd.ms-excel'); //mime type
			header('Content-Disposition: attachment;filename="'.$filename.'"'); //tell browser what's the file name
			header('Cache-Control: max-age=0'); //no cache
				             
			//save it to Excel5 format (excel 2003 .XLS file), change this to 'Excel2007' (and adjust the filename extension, also the header mime type)
			//if you want to save it as .XLSX Excel 2007 format
			$objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');  
			//force user to download the Excel file without writing it to server's HD
			$objWriter->save('php://output');
		}
	}
}
?>